package com.lingshi.shopping_cart_service.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.lingshi.shopping.constant.Constant;
import com.lingshi.shopping.constant.RedisKey;
import com.lingshi.shopping.entity.CartGoods;
import com.lingshi.shopping.service.CartService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@DubboService
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addCart(Long userId, CartGoods cartGoods) {
        String goodsId = cartGoods.getGoodId().toString();

        String key = StrUtil.format(RedisKey.SHOPPING_CART_KEY, userId);

        HashOperations<String,String,CartGoods> hos = redisTemplate.opsForHash();

        //购物车有商品，添加数量
        if(hos.hasKey(key,goodsId)){
            CartGoods cartGoods1 = hos.get(key, goodsId);
            cartGoods.setNum(cartGoods.getNum()+cartGoods1.getNum());
        }
        hos.put(key,cartGoods.getGoodId().toString(),cartGoods);
    }

    @Override
    public void handleCart(Long userId, Long goodId, Integer num) {

        String key = StrUtil.format(RedisKey.SHOPPING_CART_KEY, userId);

        HashOperations<String,String,CartGoods> hos = redisTemplate.opsForHash();
        //获取原有的购物车商品
        CartGoods cartGoods = hos.get(key, goodId.toString());
        //修改数量
        cartGoods.setNum(num);
        //重新设置
        hos.put(key,cartGoods.getGoodId().toString(),cartGoods);

    }

    @Override
    public void deleteCartOption(Long userId, Long goodId) {
        String key = StrUtil.format(RedisKey.SHOPPING_CART_KEY, userId);
        HashOperations<String,String,CartGoods> hos = redisTemplate.opsForHash();
        hos.delete(key,goodId.toString());
    }

    @Override
    public List<CartGoods> findCartList(Long userId) {
        String key = StrUtil.format(RedisKey.SHOPPING_CART_KEY, userId);
        HashOperations<String,String,CartGoods> hos = redisTemplate.opsForHash();
        List<CartGoods> cartGoodsList = hos.values(key);
        return cartGoodsList;
    }



    @Override
    public void refreshCartGoods(CartGoods cartGoods) {

    }

    @Override
    public void deleteCartGoods(Long userId,Long goodId) {
        String key = StrUtil.format(RedisKey.SHOPPING_CART_KEY, userId);
        HashOperations<String,String,CartGoods> hos = redisTemplate.opsForHash();
        hos.delete(key,goodId.toString());
    }
}
